package org.NooLab.nativebrowser.browser;

import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JPanel;


import org.NooLab.nativebrowser.app.controller.HtmlConsumerIntf;
import org.NooLab.nativebrowser.app.controller.parser.PageIntf;
import org.NooLab.nativebrowser.components.WebBrowserAppMainIntf;
import org.NooLab.nativebrowser.gui.hidden.HiddenWindowGuiIntf;
import org.NooLab.nativebrowser.retrieval.RetrievalDispatch;
import org.NooLab.nativebrowser.retrieval.RetrievalEngine;
import org.NooLab.utilities.logging.PrintLog;
import org.NooLab.utilities.objects.StringedObjects;

import chrriis.dj.nativeswing.swtimpl.components.JWebBrowser;





/**
 * 
 * 
 * 
 * 
 *
 */
public class DjBrowserHost
							extends
										Observable
							implements 
										DjBrowserHostIntf,
										Observer{


	private static final long serialVersionUID = 6737517587403134896L;

	BrowserWorker swingWorker;
	String guidStr="";
	
	WebBrowserAppMainIntf app;
	JWebBrowser webBrowser ;

	private HiddenWindowGuiIntf windowGui;
	private Observer observer;

	private PageIntf page;
	int browserOption = 1; // 1 = clear for direct browser usage
	
	private DjBrowserListener listener;
	private boolean isCollecting;

	// just for testing
	String baseurl = "http://www.google.ch/search?num=100&hl=de&site=&source=hp&q=the+putnam+program";

	private PrintLog out;

	private RetrievalDispatch retrievalDispatch;
	
	// ----------------------------------------------------------		
	public DjBrowserHost(WebBrowserAppMainIntf app){
		
		// app.webBrowserPanel = new JPanel(new BorderLayout()); // destroyOnFinalization
		// app.webBrowserPanel.setBorder(BorderFactory.createTitledBorder("Native Web Browser component"));

		this.app = app ; // new JWebBrowser(); //
		webBrowser =  new JWebBrowser(); //destroyOnFinalization(), JWebBrowser.proxyComponentHierarchy(), JWebBrowser.constrainVisibility());
		app.setWebBrowser( webBrowser );
		
		
		windowGui = app.getAppCommons().getWindowGui();
		out = app.getAppCommons().getOut();
		
		//htmlConsumer = app.getAppCommons().getHtmlConsumer();
		 
		// to storage and other processes
		// observer = (Observer) ;
		// addObserver( observer );
	}

	
	public DjBrowserHost(WebBrowserAppMainIntf app, JWebBrowser webbrowser, int size) {
		this.app = app ;
		
		webBrowser = webbrowser ;
	}
	
	public DjBrowserHost(WebBrowserAppMainIntf app, int size) {
		// 
		this.app = app ;
		
		
		webBrowser = new JWebBrowser();// JWebBrowser.destroyOnFinalization());
		
		
		// JFlashPlayer(JFlashPlayer.destroyOnFinalization());   
		app.setWebBrowser( webBrowser );
		
		
	}

	// ----------------------------------------------------------
	 
	
	
	@Override
	public void update(Observable o, Object pageStrObj) {
		/*
		 * sent by the DjBrowserListener as soon as it recognized a COMPLETION
		 */
		DjBrowserListener dj;
		
		if (out==null){
			out = app.getAppCommons().out ;
		}
		out.print(2, "BrowserHost has been informed: retrieval of webpage has been completed...");
		
		
		if ((pageStrObj !=null) && (pageStrObj instanceof String)){
			String str = (String)pageStrObj;
			if (str.length()<10){
				int k;
				k=0;
				listener.setInternalClient("BrowserHost::update (1)::"+o.getClass().toString());
				// (new BrowserWorker(webBrowser, null,listener)).execute();
			}
		}else{
			// setting page to null explicitly will clear the display
			// in order to prevent display of the google's own search box
			int k;
			k=0;
			listener.setInternalClient("BrowserHost::update (2)::"+o.getClass().toString());
			page = (PageIntf)pageStrObj;
			
			if ((page.getHTML().length()<50) || 
				((listener.getContextStr().length()==0) && ( browserOption == _OPTION_CLEAR_BROWSERACTION))){
				// (new BrowserWorker(webBrowser, null,listener)).execute();
				// here in WebBrowser, we never clear the browser window
			}
		}
		
		// rd = new new RetrievalDispatch(app,this, listener);
		String cn = o.getClass().getSimpleName().toLowerCase();
		
		try {
		
			retrievalDispatch = (new RetrievalDispatch(app,this, listener));
			retrievalDispatch.handlingData(pageStrObj);

		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

	
	@Override
	public void close() {
		if (retrievalDispatch!=null){
			retrievalDispatch.close();
		}
		retrievalDispatch=null;
		System.gc();
	}



	public void prepare( WebBrowserAppMainIntf app, boolean newWindow, DjBrowserHostIntf  browserHost){
		
		// app.windowGui still "gui = null" here !!!  getMainFrame().getPanelMetaSearchBrowser()
		// we have to relocate it later 
		// app.getMainFrame().add( app.webBrowserPanel, BorderLayout.CENTER);
	
		// app.webBrowserPanel.setVisible(false) ;
		
		// ........ the important part comes here ..........
		
		
		listener = new DjBrowserListener(this);
		listener.addObserver(this) ;
		// 
		// criss....
		webBrowser.addWebBrowserListener( listener  );
		
		// ...and cross....
		listener.establishWebBrowserWindow( app.getWindowGui(), webBrowser,newWindow);
		
		
		// ------------------
		browserHost.setListener(listener);
	
		webBrowser.setMenuBarVisible(false);
		webBrowser.setButtonBarVisible(false) ;
		
		
	}

	@Override
	public void prepare(WebBrowserAppMainIntf app, boolean newWindow) {
		
		prepare( app, newWindow, this);
	}

	@Override
	public void setUrl(String requestUrl) {
		
	}

	@Override
	public void navigate(String requestUrl) {
		
		// webBrowser.navigate(baseurl);
		listener.reset();
		listener.disable();
		int k;
		k=0;
		
		listener.setContextStr("");
		(swingWorker = new BrowserWorker( this, webBrowser, requestUrl)).execute(); // new instance
	}

	/**
	 * hot spot for calling the swingworker object for retrieving the page (=BrowserWorker)
	 * 
	 * it is called from "RetrievalEngine::RequestPerformer"
	 */
	@Override
	public void retrieve(String requestUrl) {
		
		RetrievalEngine r; // just for quick jump while developing
		
		
		listener.reset();
		listener.setContextStr("");
		listener.setActiveWebBrowser(webBrowser);
		// webBrowser.navigate(baseurl);  <--- this does not work, because it is outside AWT thread
		// instead use a SwingWorker
		(swingWorker = new BrowserWorker( this, webBrowser, requestUrl)).execute(); // new instance
		// webBrowser.setHTMLContent(str) ;
		// app.windowGui.out.print(2, str);
		 
	}

	@Override
	public void retrieve(PageIntf page, String contextStr) {
		
		String requestUrl="";

		listener.reset();
		
		this.page = page;
		listener.setPage(page);

		listener.setActiveWebBrowser(webBrowser);
		listener.setContextStr(contextStr);
		
		requestUrl = page.getContextUrl();
		
		(swingWorker = new BrowserWorker( this, webBrowser, requestUrl)).execute();
		
	}


	@Override
	public JWebBrowser getWebBrowser() {
		// 
		return webBrowser;
	}

	@Override
	public String getBaseurl() {
		// 
		return baseurl ;
	}

	@Override
	public String getGuidStr() {
		// 
		return guidStr;
	}
	
	@Override
	public void setListener(DjBrowserListener wblistener) {
		
		this.listener = wblistener;
	}

	@Override
	public DjBrowserListener getListener() {
		return listener;
	}


	@Override
	public void setPage(PageIntf page) {
		
	}


	@Override
	public void setPageReference(PageIntf page) {
		// 
		this.page = page;
	}


	@Override
	public void startCollecting() {
		// 
		isCollecting = true;
	}


	@Override
	public boolean isCollecting() {
		// 
		return isCollecting ;
	}


	@Override
	public void stopCollecting() {
		// 
		isCollecting = false;
	}



}

